package main

import (
	"fmt"
	"time"

	"github.com/fsnotify/fsnotify"

	"github.com/spf13/viper"
)

type MysqlConfig struct {
	Host string `mapstructure:"host"`
	Port int    `mapstructure:"port"`
	Per  Person `mapstructure:"person"`
}

type Person struct {
	Name string `mapstructure:"name"`
	Age  int    `mapstructure:"age"`
}

type Database struct {
	Mysql MysqlConfig `mapstructure:"mysql"`
}

func GetEnvInfo(env string) bool {
	// 读取系统环境变量
	viper.AutomaticEnv()
	return viper.GetBool(env)
}

func main() {
	debug := GetEnvInfo("MUSHOP_DEV")
	fmt.Println("debug", debug)
	configFileName := "./config-pro.yaml"
	if debug {
		configFileName = "./config-dev.yaml"
	}

	// 1.实例化一个viper
	v := viper.New()
	// 2.设置文件路径
	v.SetConfigFile(configFileName)
	// 3.读取文件
	err := v.ReadInConfig()
	if err != nil {
		panic(err)
	}

	// 5.读取成struct
	db := Database{}
	_ = v.Unmarshal(&db)
	fmt.Printf("db: %#v \n", db)

	// 动态监听配置变化
	v.WatchConfig()
	v.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("config file changed", e.Name)
		// 重新加载配置文件
		_ = v.ReadInConfig()
		_ = v.Unmarshal(&db)
		fmt.Printf("db: %#v \n", db)
	})

	time.Sleep(time.Second * 60)
}
